import Cookies from 'js-cookie'
import { getActiveMenu, setActiveMenu } from '@neu/biz-core/utils/utils'

const state = {
  sidebar: {
    opened: Cookies.get('sidebarStatus') ? !!+Cookies.get('sidebarStatus') : true,
    withoutAnimation: false
  },
  device: 'desktop',
  size: Cookies.get('size') || 'medium',
  siteTitle: '前端基础框架',
  topMenus: [],
  activeTopMenu: getActiveMenu(),
  // activeTopMenu:'',
  wsEnabled: true,
  stompConnected: false,
  autoRun: []
}

const mutations = {
  TOGGLE_SIDEBAR: state => {
    state.sidebar.opened = !state.sidebar.opened
    state.sidebar.withoutAnimation = false
    if (state.sidebar.opened) {
      Cookies.set('sidebarStatus', 1)
    } else {
      Cookies.set('sidebarStatus', 0)
    }
  },
  CLOSE_SIDEBAR: (state, withoutAnimation) => {
    Cookies.set('sidebarStatus', 0)
    state.sidebar.opened = false
    state.sidebar.withoutAnimation = withoutAnimation
  },
  TOGGLE_DEVICE: (state, device) => {
    state.device = device
  },
  SET_SIZE: (state, size) => {
    state.size = size
    Cookies.set('size', size)
  },
  SET_SITETITLE: (state, title) => {
    state.siteTitle = title
  },
  SET_TOPMENUS: (state, topMenus) => {
    state.topMenus = topMenus
  },
  SET_ACTIVETOPMENU: (state, activeTopMenu) => {
    state.activeTopMenu = activeTopMenu
  },
  SET_WS_ENABLED: (state, wsEnabled) => {
    state.wsEnabled = wsEnabled
  },
  SET_STOMP_CONNECTED: (state, stompConnected) => {
    state.stompConnected = stompConnected
  },
  SET_AUTO_RUN: (state, autoRun) => {
    state.autoRun = autoRun
  }
}

const actions = {
  toggleSideBar({ commit }) {
    commit('TOGGLE_SIDEBAR')
  },
  closeSideBar({ commit }, { withoutAnimation }) {
    commit('CLOSE_SIDEBAR', withoutAnimation)
  },
  toggleDevice({ commit }, device) {
    commit('TOGGLE_DEVICE', device)
  },
  setSize({ commit }, size) {
    commit('SET_SIZE', size)
  },
  setTitle({ commit }, title) {
    commit('SET_SITETITLE', title)
  },
  setTopMenus({ commit }, topMenus) {
    commit('SET_TOPMENUS', topMenus)
    const defaultActiveModule = topMenus.find(it => it.defaultActive)
    // commit('SET_ACTIVETOPMENU', defaultActiveModule ? defaultActiveModule.module : '')
    if (state.activeTopMenu === defaultActiveModule || !state.activeTopMenu) {
      commit('SET_ACTIVETOPMENU', defaultActiveModule ? defaultActiveModule.module : '')
    }
  },
  setActiveTopMenu({ commit }, activeTopMenu) {
    setActiveMenu(activeTopMenu)
    commit('SET_ACTIVETOPMENU', activeTopMenu)
  },
  setWsEnabled({ commit }, wsEnabled) {
    commit('SET_WS_ENABLED', wsEnabled)
  },
  setStompConnected({ commit }, stompConnected) {
    commit('SET_STOMP_CONNECTED', stompConnected)
  },
  setAutoRun({ commit }, autoRun) {
    commit('SET_AUTO_RUN', autoRun)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
